#include <assert.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>

#include "user_io.h"
#include "user_threads.h"
#include "user_mutex.h"

int global = 0;
uthread_mutex_t mutex;
int pipes[2];

int start(void * param)
{
	int i, gotFromPipe, myID ;

	myID = uthread_self();

	for( i = 0 ; i <10 ; i++) {
		uthread_mutex_lock(mutex);
		uthread_read(pipes[0], &gotFromPipe, sizeof(gotFromPipe));
        printf("Thread Id= %d global= %d got from pipe %d\n", myID, global, gotFromPipe);

		global ++;
		uthread_write(pipes[1], &myID, sizeof(myID));
		uthread_mutex_unlock(mutex);
		uthread_yield();
	}

	return 0;
}

int main()
{
	int ret, i, myID;

	ret = uthread_pipe(pipes);
	assert (ret == 0 );

	ret = uthread_mutex_init(&mutex);
	assert (ret == MUTEX_SUCCESS);

	ret = uthread_mutex_lock(mutex);
	assert ( ret == MUTEX_SUCCESS);

	myID = uthread_self();

	for (i = 0 ; i < 29 ; i++) {
		ret = uthread_create(start, NULL);
	}

	while(uthread_write(pipes[1], &myID, sizeof(myID)) == -1);

	uthread_mutex_unlock(mutex);
	uthread_yield();
	start(NULL);

	return 0;
}
